//
//  FPAuthenticationController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/22.
//

#import "FPAuthenticationController.h"
#import "FPAuthenticationHeaderView.h"
#import "FPProfileEditorController.h"
#import "FPAuthenticationFooterView.h"
#import "FPAuthenticationFooterView.h"
#import <Photos/PHPhotoLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "AFNetworking.h"
#import "FPUserIdentifierCardInfoModel.h"
#import "FPAlipayInfoView.h"
#import "FPAuthenticationProtocolFooterView.h"
#import <FinAuthLiveV5Detect/FinAuthLiveV5Detect.h>
#import <FinAuthBaseKit/FinAuthPEV5LicenseManager.h>
#import "DemoFaceLiveNetwork.h"
#import "FPMeProfileController.h"
#import "FPCustomerModel.h"
#import "FPAuthenFaceWebViewController.h"

@interface FPAuthenticationController () <UITableViewDelegate , UITableViewDataSource , TTTAttributedLabelDelegate , UINavigationControllerDelegate, UIImagePickerControllerDelegate , HJCActionSheetDelegate , UITextFieldDelegate , UIGestureRecognizerDelegate>

@property (nonatomic,strong) FPAuthenticationHeaderView *headerView;
@property (nonatomic,strong) FPAuthenticationProtocolFooterView *footerView;
@property (nonatomic , assign) BOOL isSelect;
@property (nonatomic , assign) BOOL isFront; //!< 0:人像面   1:国徽面
@property (nonatomic , strong) NSString *identifierCardURLString;

@property (nonatomic , strong) NSString *nameParam;
@property (nonatomic , strong) NSString *IDNumberParam;
@property (nonatomic , strong) NSString *frontIDCardImgURL;
@property (nonatomic , strong) NSString *backIDCardImgURL;
@property (nonatomic , strong) NSMutableArray *protocolSource;
@property (nonatomic , strong) FPAlipayInfoView *alipayInfoView;

@property (nonatomic, strong) UIImagePickerController *imagePickerController;

@property (nonatomic , assign) BOOL isAutoInput;
@property (nonatomic , assign) BOOL applyBtnEnable;

@property (nonatomic , strong) NSString *province;
@property (nonatomic , strong) NSString *cityName;
@property (nonatomic , strong) NSString *cityID;
@end

@implementation FPAuthenticationController

LazyLoadDataSource(protocolSource);

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    if (self.navigationController.viewControllers.lastObject == self) {
        self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    if (self.navigationController.interactivePopGestureRecognizer.delegate == (id<UIGestureRecognizerDelegate>)self) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }

}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    [self detainmentPopupAction];
    return NO;
}

- (void)backAction {
    [self detainmentPopupAction];
}

- (void)detainmentPopupAction {
    
    LXAlertView *alert = [[LXAlertView alloc] initDetainmentWithTitleString:@"确认退出吗" contentString:@"额度最高20万元，最快3分钟即可放款" btn1:@"去意已决" btn2:@"我再想想" alertAlertResult:^(NSInteger index) {
        
        if (index == 2) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    [alert showLXAlertView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 确保实名认证页面不显示TabBar
    self.hidesBottomBarWhenPushed = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    self.isSelect = NO;
    self.isFront = NO;
    self.isAutoInput = NO;
    self.applyBtnEnable = NO;
    
    [self initUI];
    [self getProtocol];
}

- (void)initUI {
    MJWeakSelf
    self.isSelect = NO;
    self.isAutoInput = YES;
    
    [self setTitle:@"实名认证" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    self.view.backgroundColor = [UIColor hexColor:@"#F4F6FA"];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.frame = CGRectMake(0., UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - UIDevice.safeDistanceBottom - 100.f);
    [self.view addSubview:self.tableView];
    
    self.tableView.backgroundColor = UIColor.clearColor;
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPAuthenticationHeaderView.class) owner:nil options:nil].lastObject;
    self.tableView.tableHeaderView = self.headerView;
    
    [self.headerView.alipayView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toAlipayAction)]];
    [self.headerView.manualAlipayView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toAlipayAction)]];
//    CGFloat height = 92.f / 142.f * (SCREEN_WIDTH - 72.f - 32.f);
//    self.headerView.frame = CGRectMake(0.f, 0.f, SCREEN_WIDTH, 430.f + height - 92.f);
//    self.headerView.headerHeight.constant = 325.f + height - 92.f;
    
//    self.headerView.viewHeight1.constant = height;
    
    self.footerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPAuthenticationProtocolFooterView.class) owner:nil options:nil].lastObject;
    [self.view addSubview:self.footerView];
    
    self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - 100.f - UIDevice.safeDistanceBottom, SCREEN_WIDTH, 100.f);
    [self.footerView setShadow];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom, SCREEN_WIDTH, UIDevice.safeDistanceBottom)];
    v.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:v];
    
    [self.footerView.selectImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAction)]];
    [self.footerView.selectView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAction)]];
    [self.footerView.nextBtn setTitle:@"完成，开始人脸验证" forState:(UIControlStateNormal)];
    [self.footerView.openLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openProtocolAction)]];
    
    [self.headerView.imgBack addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadImageAction:)]];
    [self.headerView.imgFront addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadImageAction:)]];
    
    self.tableView.rowHeight = 2.f;
    
    [self.footerView.nextBtn handleViewControlEvents:(UIControlEventTouchUpInside) withBlock:^{
        
        if (self.isAutoInput) {
         
            if (self.frontIDCardImgURL && self.backIDCardImgURL) {
                
                [self nextAction];
            }
            else {
                
                [self showText:@"未获取身份信息"];
                FeedBackGeneratorAction;
                return;
            }
        }
        else {
            
            if (self.headerView.manualNameTF.text.length < 1) {
                
                [self.headerView.maualNameLab shake];
                [self.headerView.manualNameTF shake];
                return;
            }
            
            if (self.headerView.manualNumberTF.text.length < 18) {
                
                [self.headerView.maualNumberLab shake];
                [self.headerView.manualNumberTF shake];
                return;
            }
            
            [self nextAction];
        }
    }];
    
    [self getProtocol];
    [self customerList];
    
    self.applyBtnEnable = NO;
    [self setApplyBtnEnable:NO];
    
    [self.headerView switchAutoInput:self.isAutoInput];
    
    self.headerView.manualNameTF.delegate = self;
    self.headerView.manualNumberTF.delegate = self;
    
    [self.headerView.leftBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        [self setApplyBtnEnable:self.applyBtnEnable];
        self.isAutoInput = YES;
        [self.headerView switchAutoInput:self.isAutoInput];
    }];
    
    [self.headerView.rightBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        [self setApplyBtnEnable:YES];
        self.isAutoInput = NO;
        [self.headerView switchAutoInput:self.isAutoInput];
    }];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if ([string isEqualToString:@""]) {
        
        return YES;
    }
    
    if ([textField isEqual:self.headerView.manualNumberTF]) {
        
        return textField.text.length < 18;
    }
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if ([textField isEqual:self.headerView.manualNameTF]) {
        
        self.nameParam = textField.text;
    }
    
    if ([textField isEqual:self.headerView.manualNumberTF]) {
        
        self.IDNumberParam = textField.text;
    }
}



- (void)openProtocolAction {
    
    self.footerView.openLab.hidden = YES;
    self.footerView.privacyLab.numberOfLines = 0;
    
    CGFloat height = 100.f - 12.f + [UIView heightWithString:self.footerView.privacyLab.text labelWidth:SCREEN_WIDTH - 56.f fontSize:12.f];
    self.tableView.frame = CGRectMake(0., UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - UIDevice.safeDistanceBottom - height);
    self.footerView.labToRight.constant = 16.f;
    self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - height - UIDevice.safeDistanceBottom, SCREEN_WIDTH, height);
    
    
    
//    [UIView animateWithDuration:.25f animations:^{
//        
//        CGFloat height = 100.f - 12.f + [UIView heightWithString:self.footerView.privacyLab.text labelWidth:SCREEN_WIDTH - 56.f fontSize:12.f];
//        self.tableView.frame = CGRectMake(0., UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - UIDevice.safeDistanceBottom - height);
//        self.footerView.labToRight.constant = 16.f;
//        self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - height - UIDevice.safeDistanceBottom, SCREEN_WIDTH, height);
//    }];
}

#pragma mark - 获取协议
- (void)getProtocol {
    
    [FPProtocolModel getProtocolWithType:(FPProtocolTypeAuthentic) success:^(NSInteger code, NSString * _Nonnull message, NSArray *list) {
        [MBManager hideLoading];
        
        [self.protocolSource removeAllObjects];
        if (code == 200) {
            
            for (FPProtocolModel *model in list) {
                
                [self.protocolSource addObject:model];
            }
            
            NSMutableString *protocolStr = NSMutableString.string;
            
            for (FPProtocolModel *model in self.protocolSource) {
                
                [protocolStr appendFormat:@"%@",model.agreementName];
            }
            
            NSString *text = [NSString stringWithFormat:@"我已阅读并同意%@", protocolStr];
            
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
            
            for (NSInteger i = 0; i < self.protocolSource.count; i ++) {
                
                FPProtocolModel *model = self.protocolSource[i];
                
                NSRange range = [text rangeOfString:[NSString stringWithFormat:@"%@", model.agreementName]];
                [NSString stringToAttribute:attStr color:MAIN_BLUE_COLOR range:range];
                
                [self.footerView.privacyLab addLinkToURL:[NSURL URLWithString:model.address] withRange:range];
            }
            
            self.footerView.privacyLab.attributedText = attStr;
            self.footerView.privacyLab.delegate = self;
        }
        
    } failure:^(NSError * _Nonnull error) {
        [MBManager hideLoading];
    }];
}

- (void)selectAction {
    
    FeedBackGeneratorAction
    
    self.isSelect = !self.isSelect;
    
    if (self.isSelect) {
     
        self.footerView.selectImgView.image = SELECT_IMG_BLUE;
    }
    else {
     
        self.footerView.selectImgView.image = UNSELECT_IMG;
    }
}

#pragma mark - TTTAttributedLabelDelegate 处理协议点击
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
 
//    [MBManager showText:url.absoluteString];
    for (FPProtocolModel *model in self.protocolSource) {
        
        if ([url.absoluteString isEqualToString:model.address]) {
            
            FPMainWebController *vc = [[FPMainWebController alloc] init];
            
            vc.model = model;
            vc.protocolType = FPProtocolTypeAuthentic;
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPBaseTableViewCell *cell;
    
    if (cell == nil) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPBaseTableViewCell.class) owner:nil options:nil].lastObject;
    }
    cell.backgroundColor = UIColor.clearColor;
    cell.userInteractionEnabled = NO;
    
    return cell;
}

#pragma mark - 去人脸核身
- (void)nextAction {
    
    if (!self.isSelect) {
        
        [FPBaseProtocolView showWithText:self.protocolSource onAction:^(NSUInteger index) {
            
            if (index == 1001) {
                
                // 拒绝
            }
            else {
                
                [self selectAction];
            }
            
        } protocolDidSelectAction:^(FPProtocolModel * _Nonnull model) {
            
//                NSLog(@"%@",model.agreementName);
            FPMainWebController *vc = [[FPMainWebController alloc] init];
            vc.model = model;
            vc.protocolType = FPProtocolTypeLogin;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        
//        FeedBackGeneratorAction
//        [self.footerView.selectImgView shake];
//        [self.footerView.privacyLab shake];
        return;
    }
    
    // 判断是否已绑定过身份证 或者有没有22岁以上
    [MBManager showLoading];
    [FPUserIdentifierCardInfoModel duplicateIdentifierWithIDCardNumber:[FPUserModel AES256Encrypt:self.IDNumberParam] success:^(NSInteger code, NSString * _Nonnull message, BOOL duplicate, BOOL ageEnough , NSString *duplicatePhoneNumber) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            if (duplicate) {
                
                NSString *notice;
                if (duplicatePhoneNumber.length) {
                    
                    NSString *phone = [duplicatePhoneNumber stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
                    notice = [NSString stringWithFormat:@"该身份证已被%@绑定，若非你本人操作，请联系客服解决。", phone];
                }
                else {
                    notice = @"该身份证已被绑定，若非你本人操作，请联系客服解决。";
                }
                //重复绑定
                LXAlertView *alert = [[LXAlertView alloc] initNoticeAlertWithTitleString:@"温馨提示" contentString:notice showBtnCounts:2 btn1:@"取消" btn2:@"联系我们" btn3:@"1" alertAlertResult:^(NSInteger index) {
                   
                    if (index == 2) {
                        
                        NSString *phoneNumber = FPUserInfoModel.sharedUserInfo.customerContact;
                        NSString *telURLString = [NSString stringWithFormat:@"tel://%@", phoneNumber];
                        NSURL *telURL = [NSURL URLWithString:telURLString];
                        
                        // 确保 URL 可以被打开
                        if ([[UIApplication sharedApplication] canOpenURL:telURL]) {
                            
                            [[UIApplication sharedApplication] openURL:telURL options:@{} completionHandler:nil];
                        }
                        else {
                            NSLog(@"无法打开电话拨号界面");
                        }
                    }
                }];
                [alert showLXAlertView];
                return;
            }
            
            if (!ageEnough) {
                
                //不够22岁
                LXAlertView *alert = [[LXAlertView alloc] initNoticeAlertWithTitleString:@"温馨提示" contentString:@"本平台暂未向22岁以下青少年开放借款，请保持合理的消费习惯。" showBtnCounts:1 btn1:@"" btn2:@"" btn3:@"我已知晓" alertAlertResult:^(NSInteger index) {
                }];
                [alert showLXAlertView];
                return;
            }
            
            // 开始人脸识别
            [self openFaceAuthFirst];
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 获取客服列表(电话)
- (void)customerList {
    
    [MBManager showLoading];
    [FPCustomerModel getCustomersSuccess:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            for (FPCustomerModel *model in list) {
                
                if ([model.ID isEqualToString:@"3"]) {
                    
                    FPUserInfoModel *m = FPUserInfoModel.sharedUserInfo;
                    m.customerContact = model.contactValue;
                    [FPUserInfoModel saveUserInfo:m];
                }
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 开始人脸识别 sdk
- (void)openFaceAuthFirst {
    [MBManager showLoading];
    MJWeakSelf
    NSString *cipherText = [self aesEncryptString:self.IDNumberParam key:@"rcb4p16wb9zj85q2"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    param[@"name"] = self.nameParam;
    param[@"idCard"] = cipherText;
    [FPUserModel faceAuthenticationWithParam:param success:^(NSString * _Nonnull message, NSInteger code, NSString * _Nonnull faceUrl, NSInteger result, NSString * _Nonnull serialNo, NSString * _Nonnull serialVersionUID, NSString * _Nonnull type) {
        // 不要在这里隐藏loading，等WebView加载完成后再隐藏
        if (code == 200) {
            FPAuthenFaceWebViewController *faceWebVC = [FPAuthenFaceWebViewController new];
            faceWebVC.faceUrl = faceUrl;
            faceWebVC.serialNo = serialNo;
            faceWebVC.authSuccessBlock = ^{
                // 埋点
                [FPRecordPointModel recordPointWithType:@"0" success:^(NSInteger code, NSString * _Nonnull message) {
                } failure:^(NSError * _Nonnull error) {
                }];
                
                [weakSelf saveUserIdentifierInfo];
            };
            [self.navigationController pushViewController:faceWebVC animated:YES];
        } else {
            [MBManager hideLoading];
            [self showText:message];
        }
    } failure:^(NSError * _Nonnull error) {
        [MBManager hideLoading];
        [self showError:error];
    }];
}
#pragma mark - 上传身份证
- (void)uploadImageAction:(UITapGestureRecognizer *)sender {
    
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitles:@"拍照" , @"相册", nil];
    [sheet show];
    
    // 人像面
    if ([sender.view isEqual:self.headerView.imgBack]) {
        
        self.isFront = 0;
    }
    // 国徽面
    else {
        self.isFront = 1;
    }
}

- (void)actionSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    UIImagePickerController *imgPC = [[UIImagePickerController alloc] init];
    imgPC.delegate = self;
    
    if (buttonIndex == 1) {
        
        // 判断设备是否有相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            self.imagePickerController = [[UIImagePickerController alloc] init];
            self.imagePickerController.delegate = self;  // 设置代理
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;  // 设置为相机
            self.imagePickerController.allowsEditing = YES;  // 是否允许编辑（裁剪）
            
            // 打开相机
            [self presentViewController:self.imagePickerController animated:YES completion:nil];
        }
        else {
            // 提示用户设备没有相机
//            NSLog(@"设备没有相机");
            [self showText:@"设备不支持相机"];
        }
    }
    else if (buttonIndex == 2) {
        
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
                // 无权限
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"无访问权限" message:@"是否跳转相机设置？" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                }];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                }];
                [alert addAction:cancel];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:^{
                }];
            }
            else {
                
                imgPC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
                    
                    [self presentViewController:imgPC animated:YES completion:nil];
                }
            }
        });
    }
}



// UIImagePickerControllerDelegate 方法：取消拍照时调用此方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    // 关闭相机界面
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    NSData *data = [self zipNSDataWithImage:image]; //UIImagePNGRepresentation(image);
    
    if (self.isFront) {
    
        self.headerView.frontFailureLab.hidden = YES;
        self.headerView.imgFront.image = [UIImage imageWithData:data];
    }
    else {
        
        self.headerView.backFailureLab.hidden = YES;
        self.headerView.imgBack.image = [UIImage imageWithData:data];
    }
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self uploadImg:data]; //UIImagePNGRepresentation(image)
}

- (NSInteger)getRandomNumber:(NSInteger)from to:(NSInteger)to {
    
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}

#pragma mark - 压缩图片
- (NSData *)zipNSDataWithImage:(UIImage *)sourceImage {
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>1280||height>1280) {
        if (width>height) {
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        }else{
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        }
        //2.宽大于1280高小于1280
    }else if(width>1280||height<1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale;
        //3.宽小于1280高大于1280
    }else if(width<1280||height>1280){
        CGFloat scale = width/height;
        height = 1280;
        width = height*scale;
        //4.宽高都小于1280
    }else{
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //进行图像的画面质量压缩
    NSData *data=UIImageJPEGRepresentation(newImage, 1.0);
    if (data.length>100*1024) {
        if (data.length>1024*1024) {//1M以及以上
            data=UIImageJPEGRepresentation(newImage, 0.7);
        }else if (data.length>512*1024) {//0.5M-1M
            data=UIImageJPEGRepresentation(newImage, 0.8);
        }else if (data.length>200*1024) {
            //0.25M-0.5M
            data=UIImageJPEGRepresentation(newImage, 0.9);
        }
    }
    return data;
}

# pragma mark - 上传图片
- (void)uploadImg:(NSData *)imageData {
    
    [MBManager showLoading];
    NSMutableDictionary *headers = NSMutableDictionary.dictionary;
    [headers setValue:@"application/json" forKey:@"Content－Type"];
    [headers setValue:@"user" forKey:@"X-User-Type"];
    
    if (FPUserModel.globalToken.length) {
        
        [headers setValue:FPUserModel.globalToken forKey:@"token"];
//        [headers setValue:@"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1ODk5ZTE1ODFhZjk0MzNjYjNiYTUxMjI5NTgzZmZmNSIsInN1YiI6IjIzMyIsImlzcyI6InNnIiwiaWF0IjoxNzQ1OTk0MjE1LCJleHAiOjE3NDYwODA2MTV9.hDvSZI2RcezRRmhhFO2ajKSJ-OZp8JLFUb8SevqmBes"
//                   forKey:@"token"];
    }
    
    // 1. 创建上传请求的 URL
    NSURL *url = [NSURL URLWithString:[MAIN_URL stringByAppendingString:UPLOAD_IDENTIFIER_CARD_URL]];
    
    // 2. 创建 AFHTTPSessionManager 实例
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 3. 设置请求头类型，告诉服务器我们传送的是 multipart/form-data 格式
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
    
    [manager setDataTaskDidReceiveDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSData * _Nonnull data) {
    
        NSLog(@"Request URL: %@", dataTask.originalRequest.URL.absoluteString);
    }];
    
    // 4. 设置图片上传的表单字段，使用 multipart/form-data 编码
    [manager POST:url.absoluteString parameters:nil headers:headers constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        // 将图片转换为 JPEG 格式并附加到请求体中
        NSData *imageData;
        if (self.isFront) {
            
            imageData = UIImageJPEGRepresentation(self.headerView.imgFront.image, 0.6);  // 压缩图片到60%质量
        }
        else {
        
            imageData = UIImageJPEGRepresentation(self.headerView.imgBack.image, 0.6);  // 压缩图片到60%质量
        }
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.jpg" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        // 进度回调
        NSLog(@"Upload Progress: %.2f%%", uploadProgress.fractionCompleted * 100);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [MBManager hideLoading];
        
        if ([responseObject isKindOfClass:NSDictionary.class]) {
            
            NSInteger code = [[responseObject objectForKey:@"code"] integerValue];
            
            if (code == 200) {
                
                if (self.isFront) {
                    
                    self.frontIDCardImgURL = [responseObject objectForKey:@"data"][@"urlPath"];
                    
#warning 国徽面不做校验
//                    [self getUserInfo];
                    
                    if (self.backIDCardImgURL.length > 0) {
                     
                        self.applyBtnEnable = YES;
                        [self setApplyBtnEnable:YES];
                    }
                }
                // 只有上传背面(人像面) 才会有身份信息
                // 这个是人像面
                else {
                    
                    self.backIDCardImgURL = [responseObject objectForKey:@"data"][@"urlPath"];
                    
                    self.identifierCardURLString = [responseObject objectForKey:@"data"][@"urlPath"];
                    
                    [self getUserInfo];
                }
            }
            else {
                
                [self showText:[responseObject objectForKey:@"msg"]];
                
                [self updoadFaild];
            }
        }
        else {
            [self showText:@"上传失败"];
            
            [self updoadFaild];
        }
        // 上传成功
        NSLog(@"Upload Success: %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        // 上传失败
        NSLog(@"Upload Failed: %@", error.localizedDescription);
    }];
}

- (void)updoadFaild {
    
    if (self.isFront) {
        
        self.frontIDCardImgURL = @"";
//                    self.headerView.imgFront.image = IMG(@"bg_identify_card_front_1");
        self.headerView.frontFailureLab.hidden = NO;
    }
    else {
        
        self.backIDCardImgURL = @"";
//                    self.headerView.imgBack.image = IMG(@"bg_identify_card_back_1");
        self.identifierCardURLString = @"";
        self.headerView.backFailureLab.hidden = NO;
    }
}

#pragma mark - 保存信息 身份证信息
- (void)saveUserIdentifierInfo {
    
    NSMutableDictionary *param = APIClient.creatAPIDictionary;
    [param setObject:self.nameParam forKey:@"idcardName"];
    
    NSString *number = [FPUserModel AES256Encrypt:self.IDNumberParam];
    [param setObject:number forKey:@"idcardNumber"];
    
    if (self.isAutoInput) {
        
        [param setObject:self.frontIDCardImgURL forKey:@"idCardImageFront"];
        [param setObject:self.backIDCardImgURL forKey:@"idCardImageReverseSide"];
    }
    
    // 入资状态判断（0未实名，1已实名，2留资1完成，3留资2完成）
    NSMutableDictionary *dic = NSMutableDictionary.dictionary;
    [dic setObject:@"1" forKey:@"status"];
    [MBManager showLoading];
    [FPUserInfoModel updateAdvertUserInfoWithParam:dic success:^(NSString * _Nonnull msg, NSInteger code) {
        
        if (code == 200) {
       
            [FPUserInfoModel updateUserInfoWithParam:param success:^(NSString * _Nonnull msg, NSInteger code) {
                [MBManager hideLoading];
                
                if (code == 200) {
                    
                    //
                    [[NSNotificationCenter defaultCenter] postNotificationName:FPAuthenticationSuccessNotification object:nil];
                    
                    [FPUserInfoModel getUserInfoWithSuccess:^(FPUserInfoModel * _Nonnull model) {
                        
                        [self signProtocolWithParams:self.protocolSource];
                        
                        // 去留资1
                        FPMeProfileController *vc = [[FPMeProfileController alloc] init];
                        
                        vc.province = self.province;
                        vc.cityName = self.cityName;
                        vc.cityID = self.cityID;
                        [self.navigationController pushViewController:vc animated:YES];
                        
                    } failure:^(NSError * _Nonnull error) {
                    }];
                }
                else {
                    
                    [self showText:msg];
                }
                
            } failure:^(NSError * _Nonnull error) {
                
            }];
        }
        else {
            
            [self showText:msg];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}



#pragma mark - 根据上传的照片获取身份信息
- (void)getUserInfo {
    [MBManager showLoading];
    [FPUserIdentifierCardInfoModel getInfoWithIDCardURL:self.identifierCardURLString success:^(NSInteger code , NSString *message , FPUserIdentifierCardInfoModel * _Nonnull model) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            NSString *idNumber = [FPUserModel AES256Decrypt:model.idNumber];
            
            self.headerView.nameLab.text = model.realname;
            self.headerView.idNumberLab.text = idNumber;
            
            self.nameParam = model.realname;
            self.IDNumberParam = idNumber;

            if (self.frontIDCardImgURL.length > 0 && self.backIDCardImgURL.length > 0) {
             
                self.applyBtnEnable = YES;
                [self setApplyBtnEnable:YES];
            }
            else {
                
                self.applyBtnEnable = NO;
                [self setApplyBtnEnable:NO];
            }
        }
        else {
            
            self.applyBtnEnable = NO;
            [self setApplyBtnEnable:NO];
            
            if (self.isFront) {
                
                self.frontIDCardImgURL = @"";
                self.headerView.frontFailureLab.hidden = NO;
            }
            else {
                
                self.backIDCardImgURL = @"";
                self.identifierCardURLString = @"";
                self.headerView.backFailureLab.hidden = NO;
                self.headerView.nameLab.text = @"";
                self.headerView.idNumberLab.text = @"";
                self.nameParam = @"";
                self.IDNumberParam = @"";
            }
            
            if (![NSString isBlankString:model.message]) {
            
                [self showText:model.message];
            }
//            else {
//                
//                [self showText:@"识别失败"];
//            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
        [self updoadFaild];
    }];
}

#pragma mark - 跳支付宝身份证页面
- (void)toAlipayAction {
    
    // 创建弹窗，指定高度为 400
    CGFloat popupHeight = 500.f;  // 根据需求调整高度
    FPCustomPopupView *popupView = [[FPCustomPopupView alloc] initWithHeight:popupHeight];
    
    self.alipayInfoView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPAlipayInfoView.class) owner:nil options:nil].lastObject;
    [popupView.contentView addSubview:self.alipayInfoView];
    self.alipayInfoView.frame = CGRectMake(0.f, 0.f, SCREEN_WIDTH, popupHeight);
    
    WeakSelf;
    self.alipayInfoView.openAlipayHandle = ^{
     
        [weakSelf openAlipay];
    };
    
    // 显示弹窗
    [popupView showInView:self.view];

}

- (void)openAlipay {
    
    // 证件中心: 60000032 实名认证: 20000038  更多: https://blog.csdn.net/weixin_48141487/article/details/134224372
    
    NSString *urlStr = @"alipays://";
    
    NSURL *alipayURL = [NSURL URLWithString:urlStr];
    
    if ([[UIApplication sharedApplication] canOpenURL:alipayURL]) {
        
        [[UIApplication sharedApplication] openURL:alipayURL options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
            
        }];
    }
    else {
        
        [self showText:@"请先安装\"支付宝\""];
    }
}

- (void)setApplyBtnEnable:(BOOL)enable {
    
    self.footerView.nextBtn.enabled = enable;
    
    if (enable) {
        
        self.footerView.nextBtn.backgroundColor = MAIN_BLUE_COLOR;
    }
    else {
        
        self.footerView.nextBtn.backgroundColor = [MAIN_BLUE_COLOR colorWithAlphaComponent:.5f];
    }
}
#pragma mark - AES加密
- (NSString *)aesEncryptString:(NSString *)string key:(NSString *)key {
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = data.length;

    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    const void *keyPtr = [key UTF8String];

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCKeySizeAES128,
                                          NULL, // ECB 不需要 IV
                                          data.bytes, dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);

    NSString *result = nil;
    if (cryptStatus == kCCSuccess) {
        NSData *encryptedData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
        result = [encryptedData base64EncodedStringWithOptions:0];
    } else {
        free(buffer);
    }

    return result;
}
@end
